package main

import (
	"crypto/ecdsa"
	"crypto/elliptic"
	"crypto/rand"
	"crypto/x509"
	"encoding/pem"
	"fmt"
	"github.com/golang-jwt/jwt/v4"
	"os"
	"time"
)

func main() {
	// 生成 ECDSA 密钥对
	privateKey, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
	if err != nil {
		fmt.Println("Error generating ECDSA key pair:", err)
		return
	}

	privateKeyBytes, err := x509.MarshalECPrivateKey(privateKey)
	if err != nil {
		panic(err)
	}

	// 将 PEM 格式的私钥写入文件
	privateKeyPem := &pem.Block{
		Type:  "EC PRIVATE KEY",
		Bytes: privateKeyBytes,
	}

	// 将公钥转换为 PEM 格式
	publicKeyBytes, err := x509.MarshalPKIXPublicKey(&privateKey.PublicKey)
	if err != nil {
		panic(err)
	}

	publicKeyPem := &pem.Block{
		Type:  "PUBLIC KEY",
		Bytes: publicKeyBytes,
	}

	// 使用公钥创建 jwt.StandardClaims
	claims := jwt.StandardClaims{
		Audience:  "users",
		ExpiresAt: time.Now().Add(time.Hour * 1).Unix(),
		Id:        "jti123",
		IssuedAt:  time.Now().Unix(),
		Issuer:    "test",
		NotBefore: time.Now().Unix(),
		Subject:   "1234567890",
	}

	// 使用私钥进行签名，并获取字符串格式的 Token
	token := jwt.NewWithClaims(jwt.SigningMethodES256, claims)
	tokenString, err := token.SignedString(privateKey)
	if err != nil {
		fmt.Println("Error creating JWT token:", err)
		return
	}

	fmt.Println("JWT token:", tokenString)
	err = pem.Encode(os.Stdout, publicKeyPem)
	if err != nil {
		fmt.Println("Error encoding public key:", err)
		return
	}

	err = pem.Encode(os.Stdout, privateKeyPem)
	if err != nil {
		fmt.Println("Error encoding private key:", err)
		return
	}
}

/*
-----BEGIN PUBLIC KEY-----
MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEbZHfioqR3L977fKpdKMKDJBy3gam
UGdtfR7ex1yx9QEofra+lLdFREZo0ETvgMNXepGgZg8OansklK1o3poENw==
-----END PUBLIC KEY-----
-----BEGIN EC PRIVATE KEY-----
MHcCAQEEIMwXaS8VXju8FMESg4RTYG+mbxX6a6KoMbcK0oM0Q0VNoAoGCCqGSM49
AwEHoUQDQgAEbZHfioqR3L977fKpdKMKDJBy3gamUGdtfR7ex1yx9QEofra+lLdF
REZo0ETvgMNXepGgZg8OansklK1o3poENw==
-----END EC PRIVATE KEY-----
*/
